package mlz.a_charset;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/*
    编码与解码
 */
public class CharSetDemo01 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "你好";
        //编码: 字符 - > 字节
        //按照默认的编码方式
        byte[] bsUTF = str.getBytes();
        //[-28, -67, -96, -27, -91, -67] UFT-8
        System.out.println(Arrays.toString(bsUTF ));

        //指定字符集 -> GBK字符集
        byte[] bsGBK = str.getBytes("GBK");
        //[-60, -29, -70, -61]
        System.out.println(Arrays.toString(bsGBK));


        //解码: 字节 -> 字符
        //默认解码方式
        String s1 = new String(bsUTF);
        System.out.println(s1);//你好

        //指定解码方式 -> 有可能出现乱码
        String s2 = new String(bsUTF, "GBK");
        System.out.println(s2);//浣犲ソ


        //解决乱码问题:
        //1.按照错误的方式进行编码
        byte[] gbks = s2.getBytes("GBK");
        //2.得到字节数组,再重新解码
        String s = new String(gbks, "UTF-8");
        System.out.println(s);

    }
}
